local name, DB = ...

local backdrop = {
	bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
	tile = true,
	tileSize = 16,
	edgeFile = "Interface\\AddOns\\combattracker\\textures\\edge",
	edgeSize = 32,
	insets = {left = 0, right = 0, top = 20, bottom = 0},
}

local function Window_OnMouseDown(self, button)
	if button == "RightButton" and IsControlKeyDown() then
		self.dataset:Clear()
	else
		self:StartMoving()
	end
end

local function Window_OnMouseUp(self)
	self:StopMovingOrSizing()
	if self.anchor then
		local p, _, r, x, y = self:GetPoint(1)
		self.anchor.anchor = p
		self.anchor.anchorTo = r
		self.anchor.offsetX = x
		self.anchor.offsetY = y
	end
end

DB.Window = DB.Frame{
	class = "Frame",
	parent = UIParent,
	constructor = function (self)
		self.MaxLines = DB.SV.MaxLines
		self.lines = {}
		self:SetBackdrop(backdrop)
		self:SetBackdropColor(.1, .1, .1)
		self:EnableMouse(true)
		self:SetToplevel(true)
		self:SetMovable(true)
		self:SetScript("OnMouseDown", Window_OnMouseDown)
		self:SetScript("OnMouseUp", Window_OnMouseUp)
		local header = self:CreateFontString(nil, "OVERLAY")
		header:SetFontObject(DB.LineFont)
		header:SetPoint("TOPLEFT", self, "TOPLEFT", 24, -14)
		header:SetPoint("TOPRIGHT", self, "TOPRIGHT", -24, -14)
		self.header = header
	end,
	Attach = function (self, dataset)
		if dataset and self.dataset ~= dataset then
			self.dataset = dataset
			dataset.window = self
			dataset:Update()
		end
	end,
	Reset = function (self)
		self.current_line = 1
	end,
	NextLine = function (self)
		local current_line = self.current_line
		if current_line > self.MaxLines then return end
		local line = self.lines[current_line]
		if not line then
			line = self:AddLine(current_line)
		else
			line:Show()
		end
		self.current_line = current_line + 1
		return line
	end,
	Finalize = function (self)
		local current_line = self.current_line
		while self.lines[current_line] do
			local line = self.lines[current_line]
			line:Hide()
			current_line = current_line + 1
		end
		self:Resize()
	end,
	AddLine = function (self, index)
		local line = DB.Line(self)
		if index == 1 then
			line:SetPoint("TOP", self, "TOP", 0, -34)
		else
			line:SetPoint("TOP", self.lines[index - 1], "BOTTOM")
		end
		self.lines[index] = line
		self:Resize()
		return line
	end,
	GetLineSize = function (self)
		return DB.SV.LineWidth, DB.SV.LineHeight
	end,
	Resize = function (self)
		local w, h = self:GetLineSize()
		self:SetSize(w + 4, h * (self.current_line - 1) + 36)
	end,
	SetName = function (self, name)
		self.header:SetText(name)
	end,
}
